<template>
  <div class="home">
    <!-- 添加Header -->
    <div class="welcome-header">
      <span>欢迎参加第一届指法大赛！{{ userName }}</span>
    </div>
    <!-- 赛前必读弹窗 -->
    <div v-if="showNotice" class="notice-modal">
      <div class="notice-content">
        <div class="notice-header">
          <span class="notice-title">赛前必读</span>
          <img src="../assets/close.png" class="notice-close" @click="showNotice = false" alt="关闭" />
        </div>
        <ol class="notice-list">
          <li>本页面为练习区，点击上方西华师范大学logo可跳转到正式比赛页面</li>
          <li>本网站的词库来源于c++官方文档，精力有限，暂未添加其他编程语言词库</li>
          <li>本次比赛将从练习区的所有模块中随机抽取100个单词（函数）作为比赛题目，限时3分钟</li>
          <li>在学院正式比赛开始前系统禁止使用者跳转到正式比赛界面</li>
          <li>比赛成绩将有3分钟内正确输入的字符数以及正确率作为评判指标</li>
          <li>祝本次参赛的同学在比赛中取得良好成绩，结束后管理员可在系统后台进行成绩Excel表导出</li>
        </ol>
        <div class="notice-footer">
          <input type="checkbox" id="noMoreNotice" v-model="noMoreNotice" @change="onNoMoreNoticeChange" />
          <label for="noMoreNotice">不再提示</label>
        </div>
      </div>
    </div>
    <img alt="Vue logo" src="../assets/cwnu.png" class="logo-img" @click="onLogoClick">
    <div class="toolbar">
      <el-select v-model="selectedList" placeholder="选择词库" size="default" style="width: 180px; height: 36px;"
        @change="onWordListChange" class="toolbar-select" :disabled="started">
        <el-option v-for="item in wordlists" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <div class="toolbar-btn-group">
        <el-button type="primary" @click="startTyping" class="toolbar-btn" :disabled="started">开始练习</el-button>
        <el-button type="success" @click="resetTyping" class="toolbar-btn">重新开始</el-button>
      </div>
    </div>
    <div v-if="started" class="typing-panel">
      <div class="typing-info">
        <span>用时：{{ elapsedTime }} 秒</span>
        <span>正确率：{{ accuracy }}%</span>
        <span>进度：{{ currentIndex + 1 }}/{{ wordList.length }}</span>
      </div>
      <div class="typing-word">
        <span v-if="currentWord" v-html="highlightedWord"></span>
      </div>
      <input v-model="userInput" @keyup.enter="checkInput" :disabled="!currentWord" placeholder="请输入上方单词并回车"
        class="typing-input" />
    </div>
    <transition name="fade">
      <div v-if="showPopup" class="word-popup">
        <a :href="popupWord.url" target="_blank">{{ popupWord.text }}</a>
        <div>{{ popupWord.desc }}</div>
      </div>
    </transition>
    <transition name="fade">
      <div v-if="showStartConfirm" class="notice-modal">
        <div class="notice-content">
          <div class="notice-header">
            <span class="notice-title">提示</span>
          </div>
          <div style="margin: 24px 0; font-size: 18px;">点击确定后开始比赛</div>
          <div style="text-align: right;">
            <button @click="handleStartConfirm"
              style="background:#42b983;color:#fff;padding:8px 24px;border:none;border-radius:4px;font-size:16px;">确定</button>
            <button @click="handleStartCancel"
              style="margin-left:12px;padding:8px 24px;border:none;border-radius:4px;font-size:16px;">取消</button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
// @ is an alias to /src
// import { ref } from 'vue'
import { ElSelect, ElOption, ElButton } from 'element-plus'
// import axios from 'axios'

export default {
  name: 'HomeView',
  components: {
    ElSelect,
    ElOption,
    ElButton
  },
  data () {
    return {
      wordlists: [
        { label: 'C++ 常用函数', value: 'cpp algorithm' },
        { label: 'C++ 容器', value: 'cpp container' },
        { label: 'Simulation Contest', value: 'Simulation contest' }
      ],
      selectedList: 'cpp algorithm',
      wordList: [],
      currentIndex: 0,
      userInput: '',
      started: false,
      startTime: null,
      elapsedTime: 0,
      timer: null,
      correctCount: 0,
      showPopup: false,
      popupWord: {},
      showNotice: true,
      noMoreNotice: false,
      userName: '',
      showStartConfirm: false // 控制弹窗显示
    }
  },
  computed: {
    currentWord () {
      return this.wordList[this.currentIndex] || null
    },
    accuracy () {
      if (this.currentIndex === 0) return 0
      return Math.round((this.correctCount / this.currentIndex) * 100)
    },
    highlightedWord () {
      if (!this.currentWord) return ''
      const target = this.currentWord.text
      const input = this.userInput
      let html = ''
      for (let i = 0; i < target.length; i++) {
        if (i < input.length) {
          if (input[i] === target[i]) {
            html += `<span class='char-correct'>${target[i]}</span>`
          } else {
            html += `<span class='char-wrong'>${target[i]}</span>`
          }
        } else {
          html += `<span class='char-default'>${target[i]}</span>`
        }
      }
      return html
    }
  },
  methods: {
    async loadWordList (listName) {
      if (listName === 'cpp algorithm') {
        const module = await import('@/assets/wordlists/cpp algorithm.ts')
        this.wordList = this.shuffle([...module.default])
      } else if (listName === 'cpp container') {
        const module = await import('@/assets/wordlists/cpp container.ts')
        this.wordList = this.shuffle([...module.default])
      } else if (listName === 'Simulation contest') {
        const module = await import('@/assets/wordlists/Simulation contest.ts')
        this.wordList = this.shuffle([...module.default])
      }
      // 未来可扩展更多词库
      // this.resetTyping()
    },
    onWordListChange (val) {
      this.selectedList = val
      this.loadWordList(val)
    },
    startTyping () {
      this.started = true
      this.startTime = Date.now()
      this.elapsedTime = 0
      this.correctCount = 0
      this.currentIndex = 0
      this.userInput = ''
      this.startTimer()
    },
    // 重新开始
    resetTyping () {
      this.started = false
      this.elapsedTime = 0
      this.correctCount = 0
      this.currentIndex = 0
      this.userInput = ''
      this.stopTimer()
    },
    startTimer () {
      this.stopTimer()
      this.timer = setInterval(() => {
        this.elapsedTime = ((Date.now() - this.startTime) / 1000).toFixed(1)
      }, 100)
    },
    stopTimer () {
      if (this.timer) clearInterval(this.timer)
      this.timer = null
    },
    checkInput () {
      if (!this.currentWord) return
      if (this.userInput.trim() === this.currentWord.text) {
        this.correctCount++
      }
      this.showWordPopup(this.currentWord)
      this.currentIndex++
      this.userInput = ''
      if (this.currentIndex >= this.wordList.length) {
        this.stopTimer()
        this.started = false
      }
    },
    showWordPopup (word) {
      this.popupWord = word
      this.showPopup = true
      setTimeout(() => {
        this.showPopup = false
      }, 2000)
    },
    shuffle (arr) {
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
          ;[arr[i], arr[j]] = [arr[j], arr[i]]
      }
      return arr
    },
    onNoMoreNoticeChange () {
      if (this.noMoreNotice) {
        localStorage.setItem('noMoreNotice', '1')
      } else {
        localStorage.removeItem('noMoreNotice')
      }
    },
    // 用户可以修改时间提前进入
    async onLogoClick () {
      // 检查是否已完成比赛
      if (localStorage.getItem('competitionCompleted') === 'true') {
        this.$alert('您已参加过比赛，请耐心等待比赛结果', '提示', {
          confirmButtonText: '确定',
          showClose: true,
          callback: () => { }
        })
        return
      }

      // 北京时间 = UTC+8
      const now = new Date()
      const nowUTC8 = new Date(now.getTime() + (8 - now.getTimezoneOffset() / 60) * 60 * 60 * 1000 - 8 * 60 * 60 * 1000)
      const target = new Date('2025-06-11T11:30:00+08:00')
      if (nowUTC8 < target) {
        this.$alert('6月15日11点30之前不能进入比赛界面！', '提示', {
          confirmButtonText: '确定',
          showClose: true
        })
      } else {
        this.showStartConfirm = true
      }
    },
    handleStartConfirm () {
      this.showStartConfirm = false
      this.$router.push('/competition')
    },
    handleStartCancel () {
      this.showStartConfirm = false
    }
  },
  mounted () {
    this.loadWordList(this.selectedList)
    if (localStorage.getItem('noMoreNotice') === '1') {
      this.showNotice = false
    }
    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    this.userName = userInfo.name || ''
  },
  beforeUnmount () {
    this.stopTimer()
  }
}
</script>

<style>
.home {
  text-align: center;
  margin-top: 30px;
}

.logo-img {
  max-width: 140px;
  width: 80vw;
  height: auto;
  display: block;
  margin: 0 auto 24px auto;
}

.typing-controls {
  margin: 20px 0;
}

.typing-panel {
  margin: 30px auto;
  max-width: 400px;
}

.typing-info {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  font-size: 16px;
}

.typing-word {
  font-size: 28px;
  font-weight: bold;
  margin: 20px 0;
}

.typing-input {
  width: 100%;
  padding: 8px;
  font-size: 18px;
  box-sizing: border-box;
}

.word-popup {
  position: fixed;
  left: 50%;
  bottom: 40px;
  transform: translateX(-50%);
  background: #fff;
  border: 1px solid #42b983;
  border-radius: 8px;
  padding: 16px 24px;
  box-shadow: 0 2px 8px rgba(66, 185, 131, 0.15);
  z-index: 1000;
  min-width: 220px;
  text-align: left;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-bottom: 18px;
}

.toolbar-select .el-input__wrapper {
  height: 36px !important;
  min-height: 36px !important;
  box-sizing: border-box;
}

.toolbar-select .el-input__inner {
  height: 36px !important;
  line-height: 36px !important;
  font-size: 15px;
}

.toolbar-btn {
  height: 33px;
  line-height: 33px;
  padding: 6px 18px;
  font-size: 15px;
  border: 1px solid #bbb;
  border-radius: 4px;
  /* background: #f7f7f7; */
  cursor: pointer;
  /* transition: background 0.2s, border 0.2s; */
}

/* .toolbar-btn:hover {
  background: #e6f7f1;
  border-color: #42b983;
} */
.toolbar-btn-group {
  display: flex;
  gap: 4px;
}

.notice-modal {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.18);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.notice-content {
  background: #fff;
  border-radius: 12px;
  padding: 32px 32px 24px 32px;
  min-width: 380px;
  max-width: 90vw;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.13);
  position: relative;
}

.notice-header {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-bottom: 18px;
}

.notice-title {
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  flex: 1;
}

.notice-close {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 28px;
  height: 28px;
  cursor: pointer;
}

.notice-list {
  font-size: 16px;
  color: #333;
  margin: 0;
  padding-left: 22px;
  word-break: break-all;
  text-align: left;
}

.notice-list li {
  margin-bottom: 10px;
  line-height: 1.7;
}

.notice-footer {
  margin-top: 18px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 15px;
  color: #666;
  user-select: none;
}

.notice-footer input[type="checkbox"] {
  margin-right: 6px;
  width: 16px;
  height: 16px;
}

.char-correct {
  color: #2ecc40;
}

.char-wrong {
  color: #ff4136;
}

.char-default {
  color: #222;
}

.welcome-header {
  background: #42b983;
  color: white;
  padding: 12px 0;
  text-align: center;
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
  letter-spacing: 1px;
}
</style>
